using System.IO;
using System.Runtime.InteropServices;

namespace ResourceLoader.Extensions
{
    public static class FileStreamExtensions
    {
        public static long Read(this FileStream fileStream, [In, Out] byte[] array, long offset, long count)
        {
            long saveIndex = 0; //读取的索引位置

            //开辟临时缓存内存
            byte[] byteArrayRead = new byte[1024 * 1024]; // 1字节*1024 = 1k 1k*1024 = 1M内存

            int prepareReadCount = 0;
            long lerpCount = 0;
            while (count > 0)
            {
                lerpCount = count;
                count -= byteArrayRead.Length;
                if (count >= 0)
                {
                    prepareReadCount = byteArrayRead.Length;
                }
                else
                {
                    prepareReadCount = (int) lerpCount;
                }

                //readCount 这个是保存真正读取到的字节数
                int realReadCount = fileStream.Read(byteArrayRead, 0, prepareReadCount);

                for (int i = 0; i < realReadCount; i++)
                {
                    array[i + saveIndex] = byteArrayRead[i];
                }

                saveIndex += realReadCount;
            }

            return saveIndex;
        }
    }
}